set(COPY_FILE_TARGET_INDEX 0)
set(COPY_DIR_TARGET_INDEX 0)

# 定义一个函数，用于将变量加1  
function(increment_variable var_name)  
    set(prev_value "${${var_name}}")  
    math(EXPR new_value "${prev_value} + 1")  
    set(${var_name} ${new_value} PARENT_SCOPE)  
endfunction()  

function(copy_file SOURCE_FILE DEST_DIR)  
    # 获取当前构建目录（通常是 CMakeLists.txt 所在的目录）  
    get_filename_component(SOURCE_PATH "${SOURCE_FILE}" ABSOLUTE)
    get_filename_component(SOURCE_FILENAME "${SOURCE_FILE}" NAME)
    get_filename_component(ABSOLUTE_DEST_DIR "${DEST_DIR}" ABSOLUTE)
      
    # 检查目录是否存在，如果不存在则创建它  
    if(NOT EXISTS ${ABSOLUTE_DEST_DIR})  
        file(MAKE_DIRECTORY ${ABSOLUTE_DEST_DIR})  
    endif() 
    # 构造源文件和目标文件的完整路径  
    set(DEST_PATH "${ABSOLUTE_DEST_DIR}/${SOURCE_FILENAME}")  
      
    # 添加自定义命令来拷贝文件  
    add_custom_command(  
        OUTPUT ${DEST_PATH}  
        COMMAND ${CMAKE_COMMAND} -E copy_if_different  ${SOURCE_PATH} ${DEST_PATH}  
        COMMENT "Copying ${SOURCE_FILE} to ${DEST_DIR}"  
        VERBATIM # 如果路径中包含空格，使用此选项来避免分割问题  
    )  
    
    set(TEMP_INDEX ${COPY_FILE_TARGET_INDEX})
    increment_variable(TEMP_INDEX)
    # 添加目标目录为构建依赖，确保在拷贝文件之前目录已经存在  
    add_custom_target(copy_file_target${TEMP_INDEX} ALL DEPENDS ${DEST_PATH})
    set(COPY_FILE_TARGET_INDEX ${TEMP_INDEX} PARENT_SCOPE)
endfunction()


function(copy_directory SOURCE_DIR DEST_DIR)
    # 假设你要从 source_dir 拷贝到 destination_dir  
    get_filename_component(ABSOLUTE_SOURCE_DIR ${SOURCE_DIR} ABSOLUTE)
    get_filename_component(DEST_DIR_FULL_NAME ${DEST_DIR} ABSOLUTE)
    # 提取源目录名称
    get_filename_component(SOURCE_DIR_NAME ${SOURCE_DIR} NAME_WE)
    set(ABSOLUTE_DEST_DIR ${DEST_DIR_FULL_NAME}/${SOURCE_DIR_NAME})

    # 拷贝整个目录及其内容  
    add_custom_command(  
        OUTPUT ${ABSOLUTE_DEST_DIR} # 如果目录不能存在，则拷贝目录
        COMMAND ${CMAKE_COMMAND} -E copy_directory ${ABSOLUTE_SOURCE_DIR} ${ABSOLUTE_DEST_DIR}  
        COMMENT "Copying ${ABSOLUTE_SOURCE_DIR} to ${DEST_DIR_FULL_NAME}"  
        VERBATIM  
    )  

    set(TEMP_INDEX ${COPY_DIR_TARGET_INDEX})
    increment_variable(TEMP_INDEX)
    # 添加一个自定义目标来触发拷贝操作  
    add_custom_target(copy_directory_target${TEMP_INDEX} ALL DEPENDS ${ABSOLUTE_DEST_DIR})
    set(COPY_DIR_TARGET_INDEX ${TEMP_INDEX} PARENT_SCOPE)
endfunction()